
<template>
  <div class="qualityEvaluation" v-loading="quanEvaLoading">
    <div class="searchBox">
      <el-form ref="form" :model="searchForm" size="mini" inline>
        <!-- <el-form-item label="水站名称">
          <el-select v-model="searchForm.waterstation" placeholder="请选择水站名称">
            <p v-for="(item, index) of stationList" :key="index">
              <el-option :label="item" :value="item"></el-option>
            </p>
          </el-select>
        </el-form-item>-->
        <el-form-item label="时间" label-width="80px">
          <el-col :span="11">
            <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              :clearable="false"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              placeholder="选择开始日期"
            ></el-date-picker>
          </el-col>
          <el-col :span="2" class="line">-</el-col>
          <el-col :span="11">
            <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              :clearable="false"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              placeholder="选择结束日期"
            ></el-date-picker>
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="greenBtn" size="mini" @click="onSubmit">确定</el-button>
          <!-- <el-button type="primary" class="greenBtn" size="mini">导出</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <el-row class="qualityAnalysis card">
      <!-- 水质达标情况分析 -->
      <div class="cardTit">
        <p class="title">水质达标情况分析</p>
      </div>
      <div class="cardCnt qualityAnalysisCnt">
        <charts :option="qualityAnalysisChart" :clickEvent="qualityAnalysisClick"></charts>
      </div>
    </el-row>
    <div class="row2 card">
      <!-- 超标站点数 -->
      <div class="cardTit">
        <p class="title">超标站点数</p>
      </div>
      <div class="cardCnt exceedNumberCnt">
        <charts :option="qualityExceedNumChart"></charts>
      </div>
    </div>
    <!-- <el-row class="row2">
      <div class="pollutionFactor card">
        主要污染因子
        <div class="cardTit">
          <p class="title">主要污染因子</p>
        </div>
        <div class="cardCnt pollutionFactorCnt">
          <div class="progressBox" v-for="(val, name) of pollFactorData" :key="name">
            <span class="proTit">{{name}}</span>
            <el-progress :show-text="false" :stroke-width="22" :percentage="parseFloat((val*100).toFixed(2))" style="width: 69%;float: left;backgroungd: red;"></el-progress>
            <span class="proVal">{{ (val*100).toFixed(2) }}%</span>
          </div>
        </div>
      </div>
      <div class="companyType card">
        涉及企业类型
        <div class="cardTit">
          <p class="title">涉及企业类型</p>
        </div>
        <div class="cardCnt companyTypeCnt">
          <el-table
            :data="companyTypeTable"
            border
            style="width: 80%;margin: 0 auto;box-shadow: 3px 3px 10px #dedede;margin-top: 35px;"
            :header-cell-style="{color: '#666', backgroundColor: '#f6f6f6'}"
          >
            <el-table-column
              prop="name"
              align="center"
              label="超标因子">
            </el-table-column>
            <el-table-column
              prop="sourceType"
              align="center"
              label="涉及企业类型">
              <template slot-scope="scope">
                <span v-for="(item, index) of scope.row.sourceType" :key="index">
                  {{item}}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-row>-->
    <el-row class="row3 exceedAnalysis card">
      <!-- 超标时段分析 -->
      <div class="cardTit">
        <p class="title">超标时段分析</p>
      </div>
      <div class="cardCnt exceedAnalysisCnt">
        <charts :option="exceedAnalysisLine"></charts>
      </div>
    </el-row>

    <el-dialog
      custom-class="factorTable"
      :visible.sync="suspensionBoxFlag"
      width="90%"
      top="0vh"
      append-to-body
    >
      <el-dialog
        :title="curStation + ' ' + curFactor + factorTableType + '数据列表'"
        top="10vh"
        :visible.sync="factorTableVisible"
        append-to-body
      >
        <el-table
          :data="factorTable"
          stripe
          max-height="600"
          v-loading="factorTableLoading"
          style="margin-top: -20px;"
        >
          <!-- <el-table-column prop="waterstation" label="水站" align="center"></el-table-column> -->
          <el-table-column prop="time" label="监测时间" align="center"></el-table-column>
          <el-table-column prop="value" label="浓度" align="center">
            <template slot-scope="scope">
              <span :class="{'TableWarnRed': factorTableType === '超标'}">{{scope.row.value}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="超标倍数" align="center" v-if="factorTableType === '超标'">
            <template slot-scope="scope">
              <span
                class="TableWarnRed"
              >{{ common.multiples(scope.row.value.split('mg')[0], standard[common.translate(curFactor, 'chinaToEng')]) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <el-row class="analysisPieData card">
        <!-- 水质达标情况分析 饼图 -->
        <div class="cardTit">
          <p class="title">
            水质达标情况分析
            <span
              style="margin-left: 12px;"
              v-loading="pieChartLoading"
              element-loading-custom-class="loadingText"
            ></span>
          </p>
        </div>
        <div class="cardCnt analysisPieDataCnt">
          <div class="chartCnt" v-for="(item, index) of pieOption" :key="index">
            <charts :option="item" :clickEvent="analysisPieDataClick"></charts>
          </div>
        </div>
      </el-row>
      <el-row class="suspensionRow2">
        <div class="pollutionFactor card">
          <!-- 主要污染因子 -->
          <div class="cardTit">
            <p class="title">主要污染因子</p>
          </div>
          <div class="cardCnt pollutionFactorCnt">
            <div class="progressBox" v-for="(val, name) of pollFactorData" :key="name">
              <span class="proTit">{{name}}</span>
              <el-progress
                :show-text="false"
                :stroke-width="22"
                :percentage="parseFloat((val*100).toFixed(2))"
                style="width: 69%;float: left;backgroungd: red;"
              ></el-progress>
              <span class="proVal">{{ (val*100).toFixed(2) }}%</span>
            </div>
          </div>
        </div>
        <div class="companyType card">
          <!-- 涉及企业类型 -->
          <div class="cardTit">
            <p class="title">涉及企业类型</p>
          </div>
          <div class="cardCnt companyTypeCnt">
            <el-table
              :data="companyTypeTable"
              border
              style="width: 80%;margin: 0 auto;box-shadow: 3px 3px 10px #dedede;margin-top: 35px;"
              :header-cell-style="{color: '#666', backgroundColor: '#f6f6f6'}"
            >
              <el-table-column prop="name" align="center" label="超标因子"></el-table-column>
              <el-table-column prop="sourceType" align="center" label="涉及企业类型">
                <template slot-scope="scope">
                  <span v-for="(item, index) of scope.row.sourceType" :key="index">{{item}}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import charts from "../components/charts.vue";
import { mapGetters, mapActions } from "vuex";
import common from "@/plugins/common";
import standard from "../plugins/standard";
export default {
  name: "qualityEvaluation",
  data() {
    return {
      // endTimeOptions: {
      //   disabledDate: (time) => {
      //     // 2592000000
      //     const startTime = new Date(this.searchForm.startTime).getTime()
      //     return time.getTime() < startTime - 2592000000 || time.getTime() > startTime + 2592000000;
      //   },
      // },

      msg: "hello qualityEvaluation!",
      quanEvaLoading: false,
      searchForm: {
        // waterstation: '',
        startTime: "",
        endTime: ""
      },
      qualityAnalysisChart: {},
      qualityExceedNumChart: {},
      exceedAnalysisLine: {},
      pieOption: {
        ph: {},
        ammoniaNitrogen: {},
        nitrogen: {},
        phosphorus: {},
        cuprum: {},
        nickel: {},
        chromium: {},
        prussiate: {}
      },
      pieDefault: {
        /**
         * 需要动态配置的选项
         *
         * title.text
         * series[0].name
         * series[0].data
         *
         */
        color: ["#5ddeb7", "#ffb35f"],
        title: {
          left: "center",
          textStyle: {
            fontSize: 14
          }
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: ({d}%)"
        },
        series: [
          {
            type: "pie",
            radius: ["40%", "50%"],
            avoidLabelOverlap: false,
            label: {
              formatter: "{b}: \n{d}%"
            }
          }
        ]
      },

      suspensionBoxFlag: false,
      pieChartLoading: false,

      factorTableVisible: false,
      allFactorResult: [],
      factorTableLoading: false,
      factorTable: [],
      factorTableType: null,
      curFactor: null,
      curStation: null,

      standard,
      common
    };
  },
  methods: {
    ...mapActions([
      "fetchQualityEvaluationChart",
      "fetchQualityEvaluationLine",
      "fetchQualityEvaDetailChart",
      "getHistoryDataChart"
    ]),
    async onSubmit() {
      this.quanEvaLoading = true;
      let res = await this.fetchQualityEvaluationChart(this.searchForm);
      if (res) {
        this.$notify.warning({
          title: "提示",
          message: res,
          duration: 2000
        });
      } else {
        await this.fetchQualityEvaluationLine(this.searchForm);
        this.configQualityAnalysisChart();
        this.configExceedNumChart();
        this.configLineChart();
      }
      this.quanEvaLoading = false;
    },
    configQualityAnalysisChart() {
      let qualityData = this.qualityData;
      this.qualityAnalysisChart = {
        color: ["#ff6341", "#2ac4e0"],
        tooltip: {
          trigger: "axis",
          // formatter: '{b}<br />{a0}: {c0}%<br />{a1}: {c1}%',
          formatter: params => {
            let str = `${params[0].name}<br />`;
            for (let i = 0; i < params.length; i++) {
              str += `<span style="display:inline-block;vertical-align: middle;border-radius: 50%;width:12px;height:12px;background: ${params[i].color.colorStops[0].color};"></span> ${params[i].seriesName}: ${params[i].value} % <br />`;
            }
            return str;
          },
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ["超标率", "达标率"]
        },
        xAxis: [
          {
            type: "category",
            data: qualityData.map(v => v.xAxis),
            axisTick: {
              inside: true
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            max: 100,
            axisLabel: {
              formatter: "{value}%"
            },
            axisTick: {
              inside: true
            }
          }
        ],
        series: [
          {
            name: "达标率",
            type: "bar",
            barWidth: 30,
            stack: "1",
            data: qualityData.map(v =>
              v.value !== null ? (100 - v.value * 100).toFixed(2) : 0.0
            ),
            itemStyle: {
              normal: {
                color: new this.$echarts.graphic.LinearGradient(0, 1, 1, 0, [
                  { offset: 0, color: "#26d4d7" },
                  { offset: 1, color: "#2eb4e9" }
                ])
              }
            }
          },
          {
            name: "超标率",
            type: "bar",
            barWidth: 30,
            stack: "1",
            data: qualityData.map(v => (v.value * 100).toFixed(2)),
            itemStyle: {
              normal: {
                color: new this.$echarts.graphic.LinearGradient(0, 1, 1, 0, [
                  { offset: 0, color: "#ff363c" },
                  { offset: 1, color: "#fd9345" }
                ])
              }
            }
          }
        ]
      };
    },
    async qualityAnalysisClick(params) {
      this.pieChartLoading = true;
      this.suspensionBoxFlag = true;
      const remind = await this.fetchQualityEvaDetailChart({
        starttime: this.searchForm.startTime,
        lasttime: this.searchForm.endTime,
        waterstation: params.name
      });
      if (typeof remind === "string") {
        this.suspensionBoxFlag = false;
        return this.$notify({
          type: "warning",
          title: "提示",
          message: remind
        });
      }
      this.configAnalysisPieChart(params.name);
      this.pieChartLoading = false;
    },
    configAnalysisPieChart(waterstation) {
      let analysisPieData = this.analysisPieData;
      let pieOption = this.pieOption;
      for (let v in pieOption) {
        pieOption[v] = JSON.parse(JSON.stringify(this.pieDefault));
      }
      for (let i = 0; i < analysisPieData.length; i++) {
        let curPie = this.pieOption[analysisPieData[i].enName];
        curPie.title.text = analysisPieData[i].name;
        curPie.series[0].name = analysisPieData[i].name;
        curPie.series[0].data = [
          {
            waterstation: waterstation,
            value: analysisPieData[i].num1,
            name: "超标率"
          },
          {
            waterstation: waterstation,
            value: analysisPieData[i].num2,
            name: "达标率",
            itemStyle: {
              borderWidth: 3,
              borderColor: "#fff"
            }
          }
        ];
      }
    },
    configLineChart() {
      let quaEvaLine = this.quaEvaLine;
      this.exceedAnalysisLine = {
        color: ["#5feac8"],
        title: {
          text: "超标时段分析",
          left: "center",
          textStyle: {
            fontSize: 14,
            fontWeight: 500
          }
        },
        xAxis: {
          type: "category",
          name: "时间",
          data: quaEvaLine.map(v => v.period * 2 + ":00"),
          axisLine: {
            show: false
          },
          axisTick: {
            show: false,
            inside: true
          }
        },
        yAxis: {
          type: "value",
          name: "超标次数 / 次",
          minInterval: 1,
          axisLine: {
            show: false
          },
          axisTick: {
            show: false,
            inside: true
          }
        },
        tooltip: {
          trigger: "axis",
          formatter: "{b}时: 超标{c}次",
          axisPointer: {
            type: "shadow"
          }
        },
        series: [
          {
            data: quaEvaLine.map(v => v.counts),
            type: "bar",
            // smooth: true
            barWidth: 30
          }
        ]
      };
    },
    configExceedNumChart() {
      // 超标站点数
      let qualityExceedNum = this.qualityExceedNum;
      this.qualityExceedNumChart = {
        color: ["#feac40"],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        xAxis: [
          {
            type: "category",
            splitArea: { show: true },
            axisTick: {
              inside: true
            },
            data: qualityExceedNum.map(v => common.translate(v.xAxis))
          }
        ],
        yAxis: [
          {
            name: "超标站点数 / 个",
            type: "value",
            splitArea: { show: true },
            max: 8,
            axisTick: {
              inside: true
            }
          }
        ],
        series: [
          {
            name: "超标站点数",
            type: "bar",
            barWidth: 30,
            stack: "1",
            data: qualityExceedNum.map(v => v.value)
          }
        ]
      };
    },
    async analysisPieDataClick(params) {
      this.factorTableVisible = true;
      this.factorTableLoading = true;

      const waterstation = params.data.waterstation;
      /**
       * 这里比较特殊 为了匹配上 水站简称 和 全称
       * 如果水站简称长度大于4 则用前两位来匹配水站全称
       * 反之水站简称长度小于4 则用整个简称来匹配水站全称
       */
      this.curStation = this.stationList.find(v =>
        v.includes(
          waterstation.length > 4 ? waterstation.slice(0, 2) : waterstation
        )
      );
      this.curFactor = params.seriesName;
      this.factorTableType = params.name.replace(/率/, "");

      this.factorTable = [];
      let result = await this.getHistoryDataChart({
        starttime: this.searchForm.startTime,
        lasttime: this.searchForm.endTime,
        isExcel: "no",
        waterstation: this.curStation
      });
      let factor = common.translate(params.seriesName, "chinaToEng");
      factor = factor === "pH" ? "ph" : factor; //fixed ph or pH
      const unit = params.seriesName !== "pH" ? " mg / L" : "";
      if (this.factorTableType === "超标") {
        for (let i = 0; i < result.length; i++) {
          this.factorIsExceed(this.standard[factor], result[i][factor]) &&
            this.factorTable.push({
              time: result[i].gmtMonitor,
              waterstation: result[i].waterstation,
              value: result[i][factor] + unit
            });
        }
      } else {
        for (let i = 0; i < result.length; i++) {
          !this.factorIsExceed(this.standard[factor], result[i][factor]) &&
            this.factorTable.push({
              time: result[i].gmtMonitor,
              waterstation: result[i].waterstation,
              value: result[i][factor] + unit
            });
        }
      }
      this.allFactorResult = result;
      this.factorTableLoading = false;
    },
    factorIsExceed(standard, factorVal) {
      /**
       * factorIsExceed
       *
       * standard 标准值 Number | Object
       * factorVal 因子值 Number
       *
       * 函数用于判断因子是否超标
       * 超标返回 true   没超标返回 false
       */
      if (typeof standard === "object") {
        /** ph standard */
        return !(factorVal > standard.min && factorVal < standard.max);
      } else {
        return factorVal > standard;
      }
    },
    randomData(max, len) {
      let resData = [];
      for (let i = 0; i < len; i++) {
        resData.push(parseInt(Math.random() * max) + 1);
      }
      return resData;
    }
  },
  computed: {
    ...mapGetters({
      stationList: "getStationList",
      qualityData: "getQualityData",
      analysisPieData: "getAnalysisPieData",
      qualityExceedNum: "getQualityExceedNum",
      pollFactorData: "getPollFactorData",
      companyTypeTable: "getCompanyTypeTable",
      quaEvaLine: "getQuaEvaLine"
    })
  },
  mounted() {},
  created() {
    //search 默认值操作
    // this.searchForm.waterstation = this.stationList ? this.stationList[0] : '沙江4#'
    this.searchForm.startTime = common.changeDateToString(
      new Date(new Date().getTime() - 2592000000)
    );
    this.searchForm.endTime = common.changeDateToString(new Date());
    this.onSubmit();
  },
  components: {
    charts
  }
};
</script>
<style scoped>
.searchBox {
  background: #fff;
  padding: 20px;
}
.searchBox .line {
  text-align: center;
}

/* card */
.card {
  margin-top: 15px;
  padding: 0 20px 20px 20px;
  background: #fff;
}
.card .cardTit {
  position: relative;
  height: 60px;
  line-height: 60px;
  border-bottom: 1px solid #ececec;
  margin-bottom: 20px;
  padding-left: 15px;
}
.card .cardCnt {
}
.cardTit p::before {
  content: "";
  position: absolute;
  width: 5px;
  height: 20px;
  background: #2399ff;
  top: 50%;
  margin-top: -10px;
  left: 0;
}

/* row1 */
.qualityAnalysisCnt {
  width: 100%;
  height: 450px;
}

/* row2 */
.exceedNumberCnt {
  width: 100%;
  height: 350px;
}
.suspensionRow2 {
  display: flex;
  justify-content: space-between;
}
.suspensionRow2::before,
.suspensionRow2::after {
  content: none;
}
.pollutionFactor {
  width: 40%;
  height: 350px;
  margin-right: 2%;
}
.pollutionFactorCnt {
  /* height: calc(100% - 60px); */
  padding: 46px 0;
}
.pollutionFactorCnt .progressBox {
  overflow: hidden;
  margin-bottom: 35px;
}
.progressBox >>> .el-progress-bar__inner {
  background-image: linear-gradient(90deg, #ffd2a8 0%, #ff5858 100%);
}
.pollutionFactorCnt .progressBox:last-child {
  margin-bottom: 0;
}
.pollutionFactorCnt .progressBox .proVal {
  float: left;
  text-align: center;
  width: 15%;
}
.pollutionFactorCnt .progressBox .proTit {
  float: left;
  width: 16%;
  text-align: left;
}
.companyType {
  width: 58%;
  height: 350px;
}
.companyType .companyTypeCnt {
  width: 100%;
}

/* row3 */
.row3 {
}
.exceedAnalysisCnt {
  height: 400px;
}

.analysisPieData {
  padding: 0 20px 20px 20px;
}
.analysisPieDataCnt {
  display: flex;
  flex-wrap: wrap;
}
.analysisPieDataCnt .chartCnt {
  width: 25%;
  height: 200px;
}

@media (min-width: 1600px) {
  .pollutionFactorCnt {
    padding-left: 20px;
  }
}
</style>
<style>
.factorTable .el-dialog__body {
  padding-top: 0;
}
.factorTable .el-dialog__header {
  background-image: none;
  height: 20px;
  padding: 0;
}
.factorTable .el-dialog__headerbtn .el-dialog__close {
  color: #666;
}
.loadingText .el-loading-spinner .circular {
  height: 30px;
  width: 30px;
}
</style>
